<?php
/**
 * Desc:
 * User: hollowcg@foxmail.com
 * Date: 2019/5/25
 */

namespace app\common\model;


use think\Db;
use think\Model;

class Menu extends Model
{
    /**
     * 页面菜单
     * @return array|bool|false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getDataAdminMenu($child_key_name='children',$RoleId=''){

        $data = Db::name('menu')->where('model','admin')->order('sort asc,id desc')->select();
//        角色权限默认选中
        if (!empty($RoleId)){
            $menuIds = Db::name('userRole')->where('id',$RoleId)->value('menu_id');
            $menuIds = explode(',',$menuIds);
            if (!empty($data)){
                foreach ($data as $k=>$v){
                    if (in_array($v['id'],$menuIds)){
                        $data[$k]['checked'] = true;
                    }
            }
            }
        }

        $data = array2tree($data,'pid',$child_key_name);
        return $data;
    }
    /**
     * 菜单管理
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getDataTree(){
        $data = Db::name('menu')->where('model','admin')->order('sort asc,id desc')->select();
        return apiResult(tree($data),0,'ok');
    }

    /**
     * 保存数据
     * @param $data
     * @param $id
     * @return array
     */
    public static function saveData($data,$id){

        if ($data['pid'] == 0){
            $data['level'] = 1;
        }else{
            $data['level'] = Db::name('menu')->where('id',$data['pid'])->value('level') + 1;
        }


        $menu = \model('menu');

        try{

            $validate = [
                'title'=>'require|unique:menu'
            ];

            if (empty($id)){
                $result = $menu->validate($validate)->allowField(true)->isUpdate(false)->save($data);
            }else{
                $result = $menu->validate($validate)->allowField(true)->isUpdate(true)->save($data,['id'=>$id]);
            }

            if(false === $result){
                // 验证失败 输出错误信息
                return apiResult('',1,$menu->getError());
            }

            return apiResult(\model('menu')->getLastInsID(),0,'操作成功');

        }catch (\Exception $e){
            return apiResult('',1,$e->getMessage());
        }
    }

}